﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using COMOSOFT.Class;
using COMOSOFT.Main;
using DevExpress.XtraGrid.Columns;
using System.IO;

namespace COMOSOFT.OrderBusiness.Forms
{
    public partial class TabGeneralView : Form
    {
        ClassShare cls = new ClassShare("TabGeneralView");
        Task tak = null;
        FrmMain frmain = null;
        int flag = 0,year,numrow;    
        string path;
        object month,cid;
        DataTable dbTemp = null;
        Image img;
        bool add = false;
        string sql;
        string Cusname, Group, AddressCus, Phone, AccountName, BankAccount, AddressBank, SwiftCode, Field, Vendor, Remarks;
        public TabGeneralView(FrmMain frm)
        {
            InitializeComponent();
            this.frmain = frm;
        }

        #region [Refresh data]
        public void RefreshData()
        {
            try
            {
                sp_GeneralViewTableAdapter.Fill(dataSetOrderManagement.sp_GeneralView, ClassShare.Usid,0,year,month,cid);                          
                sp_CustomerListTableAdapter.Fill(dataSetOrderManagement.sp_CustomerList, ClassShare.Usid);
                sp_OrderStyleListTableAdapter.Fill(dataSetOrderManagement.sp_OrderStyleList, ClassShare.Usid);
                orderSizeBreakdownTableAdapter.Fill(dataSetOrderManagement.OrderSizeBreakdown);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region[Load GeneralView]
        public void LoadGV(int y, object m, object cid)
        {            
            this.year = y;
            this.month = m;            
            this.cid = cid;
            flag = 0;
            radioGroup_Menu.SelectedIndex = 0;
            radioGroup_Menu.Properties.Items[1].Description = "On Going " + this.year.ToString();
            radioGroup_Menu.Properties.Items[2].Description = "All Order " + this.year.ToString();
            radioGroup_Menu.Properties.Items[0].Description = "Waiting For Approve " + this.year.ToString();
            CallGeneral(y, m, cid);
        }      
        public void CallGeneral(int y, object m, object cid)
        {
            try
            {
                if (tak == null || tak.Status != TaskStatus.Running)
                {
                    cls.LoadLayout(gridView_Order, ClassShare.lcOrder + "LayOutGaneralView.XML");
                    splashScreenManager1.ShowWaitForm();                  
                    gridControlGaneral.DataSource = null;
                    tak = Task.Factory.StartNew(() => LoadGaneral(y, m, cid));
                    tak.ContinueWith(tt => FillTable());
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private delegate void dlgFillTable();
        private void FillTable()
        {
            try
            {
                if (InvokeRequired)
                {
                    this.Invoke(new dlgFillTable(FillTable));
                }
                else
                {
                    gridControlGaneral.DataSource = dataSetOrderManagement.sp_GeneralView;
                    splashScreenManager1.CloseWaitForm();
                }
            }
            catch 
            {
                MessageBox.Show("Progess fail");
            }
        }
        private void LoadGaneral(int y, object m, object cid)
        {
            try
            {
                sp_GeneralViewTableAdapter.Fill(dataSetOrderManagement.sp_GeneralView, ClassShare.Usid, flag, y, m, cid);                
                sp_CustomerListTableAdapter.Fill(dataSetOrderManagement.sp_CustomerList, ClassShare.Usid);
                sp_OrderStyleListTableAdapter.Fill(dataSetOrderManagement.sp_OrderStyleList, ClassShare.Usid);
                orderSizeBreakdownTableAdapter.Fill(dataSetOrderManagement.OrderSizeBreakdown);
                   
                dbTemp = new DataTable();
                dbTemp.Columns.Add("ID");
                dbTemp.Columns.Add("Img", typeof(object));
                DataTable dbMA = dataSetOrderManagement.sp_GeneralView;
                numrow = dbMA.Rows.Count;
                for (int i = 0; i < dbMA.Rows.Count; i++)
                {
                    DataRow newrow = dbTemp.NewRow();                    
                    if (dbMA.Rows[i]["Image"].ToString()!= "")
                    {
                        if (!File.Exists(ClassShare.lcOrder+ dbMA.Rows[i]["Image"].ToString()))
                            cls.Dowload(ClassShare.ftpOrder,ClassShare.lcOrder, dbMA.Rows[i]["Image"].ToString());
                        path = ClassShare.lcOrder + dbMA.Rows[i]["Image"].ToString();
                        byte[] img = System.IO.File.ReadAllBytes(path);
                        newrow["Img"] = img;
                    }
                    else
                    {
                        if (!File.Exists(ClassShare.lcMaterial + "noImage.gif"))
                           cls.Dowload(ClassShare.ftpOrder, ClassShare.lcMaterial, "noImage.gif");
                        path = ClassShare.lcMaterial + "noImage.gif";
                        byte[] NoImg = System.IO.File.ReadAllBytes(path);
                        newrow["Img"] = NoImg;
                    }
                    newrow["ID"] = dbMA.Rows[i]["OID"];
                    dbTemp.Rows.Add(newrow);
                }                             
            }
            catch
            {
                MessageBox.Show("Disconnection database! You can try later");
            }
        }
        #endregion

        #region [Update Orderdetails]
        private void gridView_Order_InitNewRow(object sender, InitNewRowEventArgs e)
        {
            if (dataSetOrderManagement.sp_GeneralView.Rows.Count > 0)
            {
                gridView_Order.SetRowCellValue(e.RowHandle, "EID",ClassShare.Usid);
                gridView_Order.SetRowCellValue(e.RowHandle, "PORCVD", DateTime.Now);
                gridView_Order.SetRowCellValue(e.RowHandle, "CusExDate",DateTime.Now);
                gridView_Order.SetRowCellValue(e.RowHandle, "Type", "Product");
                gridView_Order.SetRowCellValue(e.RowHandle, "Status", "Waiting");
            }
        }
        private void gridView_Order_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            try
            {
                GridView view =sender as GridView;
                int USID = Convert.ToInt32(view.GetFocusedDataRow()["EID"]);
                if (ClassShare.Usid == USID)
                {
                    spGeneralViewBindingSource.EndEdit();
                    sp_GeneralViewTableAdapter.Update(dataSetOrderManagement.sp_GeneralView);
                    dataSetOrderManagement.sp_GeneralView.AcceptChanges();

                    int OID = Convert.ToInt32(gridView_Order.GetFocusedDataRow()["OID"]);
                    cls.UpdateData("sp_OrderInsertImage", new string[] { "@OID", "@Image" }, new object[] { OID, path });                    
                }
                else
                {
                    MessageBox.Show("You don't permission!", "Can't update....", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                LoadGV(year, month, cid);
            }
            catch 
            {
                MessageBox.Show("Upadate Failed!");
            }
        }       
        #endregion

        #region [Filter OrderStyleList]
        private void repositoryItemGridLookUpEdit_StyleList_Click(object sender, EventArgs e)
        {
            try
            {
                GridLookUpEdit glk = sender as GridLookUpEdit;
                GridView view = glk.Properties.View as GridView;
                view.ActiveFilterString = "[Customer] = '" + gridView_Order.GetFocusedRowCellValue("Customer").ToString() + "'";
            }
            catch
            { 
            }
        }
        #endregion

        #region[Update OrderStyleList]
        private void reposStyleListView_InitNewRow(object sender, InitNewRowEventArgs e)
        {
            GridView view = sender as GridView;
            if (dataSetOrderManagement.sp_OrderStyleList.Rows.Count > 0)
            {
                view.SetRowCellValue(e.RowHandle, "Customer", gridView_Order.GetFocusedDataRow()["Customer"]);
                view.SetRowCellValue(e.RowHandle, "Creater", gridView_Order.GetFocusedDataRow()["EID"]);
            }
        }
        private void reposStyleListView_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            try
            {
                spOrderStyleListBindingSource.EndEdit();
                sp_OrderStyleListTableAdapter.Update(dataSetOrderManagement.sp_OrderStyleList);
                dataSetOrderManagement.sp_OrderStyleList.AcceptChanges();
            }
            catch
            {
                MessageBox.Show("Please try again!!","Not Insert...",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
        }

        private void deleteToolStripMenuItem_delete_Click(object sender, EventArgs e)
        {
            try
            {
                if (XtraMessageBox.Show("Are you sure?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    string styleno=gridView_Order.GetFocusedDataRow()["StyleNo"].ToString();
                    spOrderStyleListBindingSource.EndEdit();
                    sp_OrderStyleListTableAdapter.Delete(styleno);
                    sp_OrderStyleListTableAdapter.Update(dataSetOrderManagement.sp_OrderStyleList);
                    dataSetOrderManagement.sp_OrderStyleList.AcceptChanges();
                }
            }
            catch
            {
                MessageBox.Show("Can't delete object");
            }
        }
        #endregion

        #region [RepossStyleListView_DoubleClick]
        private void reposStyleListView_DoubleClick(object sender, EventArgs e)
        {
            reposStyleListView.Columns["Customer"].Visible = true;
            reposStyleListView.Columns["Description"].Visible = true;
            reposStyleListView.Columns["ItemGroup"].Visible = true;
            reposStyleListView.Columns["Creater"].Visible = true;
            reposStyleListView.Columns["Remarks"].Visible = true;
        }
        #endregion

        private void TabGeneralView_Load(object sender, EventArgs e)
        {          
            this.employeeTableAdapter.Fill(this.dataSetOrderManagement.Employee);           
        }

        #region [Order Status]
        private void radioGroup_Menu_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (radioGroup_Menu.SelectedIndex == 0)
                {
                    flag = 0;
                }
                else 
                {
                    if (radioGroup_Menu.SelectedIndex == 1)
                        flag = 1;
                    else 
                    {
                        if (radioGroup_Menu.SelectedIndex == 2)
                            flag = 2;
                        else
                            flag = 3;
                    }
                    
                }
                
                this.month = null;
                this.cid = null;
                CallGeneral(year, month, cid);
            }
            catch
            {
                MessageBox.Show("Not access database!");
            }
        }
        #endregion        

        #region[Radial Menu]
        private void Radial_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            radialMenu_Order.Collapse(false);
            switch (e.Item.Caption)
            {
                case "Delete Order":
                    try
                    {
                        if (gridView_Order.FocusedRowHandle >= 0)
                        {                            
                            if (XtraMessageBox.Show("Are you sure?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                            {
                                spGeneralViewBindingSource.EndEdit();
                                gridView_Order.DeleteSelectedRows();
                                sp_GeneralViewTableAdapter.Update(dataSetOrderManagement.sp_GeneralView);
                                dataSetOrderManagement.sp_GeneralView.AcceptChanges();
                            }
                        }
                    }
                    catch
                    {
                        MessageBox.Show("Can't delete object");
                    }
                    break;
                case "SizeBreakDown":
                    if (gridView_Order.FocusedRowHandle >= 0)
                    {
                        radialMenu_Order.Collapse(false);
                        int OID = Convert.ToInt32(gridView_Order.GetFocusedDataRow()["OID"]);
                        FrmSizeBreakdown frSBD = new FrmSizeBreakdown();
                        frSBD.OIDs.Add(OID);
                        frSBD.Show();                        
                    }
                    break;
                case "Factory Purchase":
                    try
                    {
                        if (gridView_Order.FocusedRowHandle >= 0)
                        {                           
                            FrmFactoryPurchaseMaster frFPM = new FrmFactoryPurchaseMaster(-1) { MdiParent = this.frmain, Text = "PO: Add new Factory Purchase" };
                            int[] numrow = gridView_Order.GetSelectedRows();
                            foreach (int i in numrow)
                            {
                                DataRow row = gridView_Order.GetDataRow(i);
                                if (i == 0)
                                    frFPM.OIDS = row["OID"].ToString();
                                else
                                    frFPM.OIDS += "," + row["OID"].ToString();
                            }
                            frFPM.Show();
                            frFPM.LoadFPM();
                            frFPM.NewFPM();
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    break;
                case "Refesh":                    
                    sp_GeneralViewTableAdapter.Fill(dataSetOrderManagement.sp_GeneralView, ClassShare.Usid, 0, year, month, cid);
                    orderSizeBreakdownTableAdapter.Fill(dataSetOrderManagement.OrderSizeBreakdown);
                    break;
                case "Export":
                    FrmExportExcel expt = new FrmExportExcel();
                    expt.LoadData(gridView_Order);
                    expt.Show();
                    break;
                case "Load Layout":
                    cls.LoadLayout(gridView_Order, ClassShare.lcOrder + "LayOutGaneralView.XML");
                    break;
                case "Save Layout":
                    cls.SaveLayout(gridView_Order, ClassShare.lcOrder + "LayOutGaneralView.XML");
                    break;                   
                default:
                    break;
                    
            }
        }
        #endregion

        #region[Right Click]
        private void gridControlGaneral_MouseClick(object sender, MouseEventArgs e)
        {
            if (gridView_Order.FocusedRowHandle >= 0)
            {
                if (e.Button == MouseButtons.Right)
                {
                    radialMenu_Order.ShowPopup(Control.MousePosition, true);
                }
            }
        }
        #endregion

        #region[LoadImage]
        private void gridView_Order_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            try
            {
                DataRowView row = e.Row as DataRowView;
                GridView view = sender as GridView;               
                if (!view.IsNewItemRow(e.ListSourceRowIndex) && numrow > e.ListSourceRowIndex)
                {
                   if(e.Column.FieldName == "colImage" && e.IsGetData)
                    e.Value = LoadImg(row["OID"].ToString(), e.ListSourceRowIndex);
                }
            }
            catch 
            {                
            }
        }

        private void repositoryItemImageEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                if (e.Button.Tag.ToString() == "Add")
                {
                    OpenFileDialog dlg = new OpenFileDialog();
                    dlg.InitialDirectory = @"C:\";
                    dlg.Filter = "All file (*.*)|*.*|JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif";
                    dlg.Title = "Please select an image file to encrypt.";
                    if (dlg.ShowDialog() == DialogResult.OK)
                    {
                        string name = Path.GetFileName(dlg.FileName);
                        cls.UploadFile(dlg.FileName, ClassShare.ftpOrder);
                        path = name;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private Image LoadImg(string ID, int row)
        {
            try
            {
                if (dbTemp.Rows.Count > row && dbTemp.Rows[row]["ID"].ToString() == ID)
                {
                    using (System.IO.MemoryStream str = new System.IO.MemoryStream(dbTemp.Rows[row]["Img"] as byte[]))
                    {
                        img = Image.FromStream(str);
                        return img;
                    }
                }
            }
            catch 
            {
            }
            return img;
        }
        #endregion

        private void HideButton(bool val1,bool val2)
        {            
            dataNavigator_Customer.Buttons.CustomButtons[2].Enabled = val1;
            dataNavigator_Customer.Buttons.CustomButtons[0].Enabled = val2;
            dataNavigator_Customer.Buttons.CustomButtons[3].Enabled = val2;
            groupControl_CustomerList.Enabled = val2;
        }
        //Update Customer
        #region [Update Customer]
        private void repositorycustomerList_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                if (e.Button.Tag.ToString() == "Add")
                {
                    HideButton(false, true);
                    sp_CustomerListTableAdapter.Fill(dataSetOrderManagement.sp_CustomerList, ClassShare.Usid);
                    txt_CustomerName.Properties.ReadOnly = true;
                    dockPanel_Customer.Show();
                }
            }
            catch
            {               
            }
        }
        private void dataNavigator_Customer_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {
            switch (e.Button.Tag.ToString())
            {
                case "Add":
                    HideButton(true, false);
                    txt_CustomerName.Properties.ReadOnly = false;
                    txt_CustomerName.Focus();
                    txt_CustomerName.Text="";
                    txt_Group.Text = "";
                    txt_Address.Text = "";
                    txt_Phone.Text = "";
                    txt_AccountName.Text = "";
                    txt_BankAccount.Text = "";
                    txt_BankAddress.Text = "";
                    txt_SwiftCode.Text = "";
                    txt_Feild.Text = "";
                    txt_Vendor.Text = "";
                    txt_Remarks.Text = "";
                    add=true;
                    break;
                case "Save":
                    try
                    {
                        Cusname = txt_CustomerName.Text;
                        Group = txt_Group.Text;
                        AddressCus = txt_Address.Text;
                        Phone = txt_Phone.Text;
                        AccountName = txt_AccountName.Text;
                        BankAccount = txt_BankAccount.Text;
                        AddressBank = txt_BankAddress.Text;
                        SwiftCode = txt_SwiftCode.Text;
                        Field = txt_Feild.Text;
                        Vendor = txt_Vendor.Text;
                        Remarks = txt_Remarks.Text;
                        if (add == false)
                        {
                            sql = "sp_CustomerUpdate";
                        }
                        else
                        {
                            sql = "sp_CustomerInsert";
                        }
                        cls.UpdateData(sql, new string[] { "@Customer", "@Group", "@AddressCus", "@Phone", "@AccountName", "@BankAccount", "@AddressBank", "@SwiftCode", "@Field", "@Vendor", "@Remarks", "@EID" },
                                          new object[] { Cusname, Group, AddressCus, Phone, AccountName, BankAccount, AddressBank, SwiftCode, Field, Vendor, Remarks, ClassShare.Usid });
                        sp_CustomerListTableAdapter.Fill(dataSetOrderManagement.sp_CustomerList, ClassShare.Usid);
                        HideButton(false, true);
                        txt_CustomerName.Properties.ReadOnly = true;
                        add =false;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }

                    break;
                case "Cancel":
                    HideButton(false, true);
                    gridView_CustomerList.FocusedRowHandle = 0;
                    txt_CustomerName.Properties.ReadOnly = true;
                    break;
                case "Refresh":
                    sp_CustomerListTableAdapter.Fill(dataSetOrderManagement.sp_CustomerList, ClassShare.Usid);
                    break;
                case "Exit":
                    dockPanel_Customer.Hide();
                    break;
            }
        }
        #endregion      

        private void gridView_CustomerList_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            try
            {
                GridView view = sender as GridView;
                txt_CustomerName.Text = view.GetFocusedDataRow()["Customer"].ToString();
                txt_Group.Text = view.GetFocusedDataRow()["Group"].ToString();
                txt_Address.Text = view.GetFocusedDataRow()["AddressCus"].ToString();
                txt_Phone.Text = view.GetFocusedDataRow()["Phone"].ToString();
                txt_AccountName.Text = view.GetFocusedDataRow()["AccountName"].ToString();
                txt_BankAccount.Text = view.GetFocusedDataRow()["BankAccount"].ToString();
                txt_BankAddress.Text = view.GetFocusedDataRow()["AddressBank"].ToString();
                txt_SwiftCode.Text = view.GetFocusedDataRow()["SwiftCode"].ToString();
                txt_Feild.Text = view.GetFocusedDataRow()["Field"].ToString();
                txt_Vendor.Text = view.GetFocusedDataRow()["Vendor"].ToString();
                txt_Remarks.Text = view.GetFocusedDataRow()["Remarks"].ToString();
            }
            catch
            {
            }
        }

        private void repositoryItemGridLookUpEdit_StyleList_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Tag.ToString() == "Add")
            {
                dockPanel_Style.Show();
            }
        }

        #region [Style List]
        private void dataNavigator_Style_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {
            switch (e.Button.Tag.ToString())
            {
                case "Add":
                    break;
                case "Save":
                    break;
                case "Delete":
                    break;
                case "Refresh":                    
                    break;
                case "Exit":
                    dockPanel_Style.Close();
                    break;                    
            }
        }
        #endregion
    }
}
